import axios from './api_config';
import path from './api_path';
import moment from 'moment'
// import {appRouter} from '@/router/router';


let util = {};
util.path = path;

util.title = function (title) {
  title = title || 'Asoco';
  window.document.title = title;
};

// 自定义请求
//delete请求
util.fetchDeleteObj = function (url, params = {}) {
  return new Promise((resolve, reject) => {
    axios({
      method: 'delete',
      url: url,
      data: params,
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'token': window.localStorage.getItem('token'),
      }
    }).then((response) => {
      resolve(response.data);
    }).catch(err => {
      reject(err)
    });
  });
};


// put请求
util.fetchPutObj = function (url, params = {}) {
  return new Promise((resolve, reject) => {
    axios({
      method: 'put',
      url: url,
      data: params,
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'token': window.localStorage.getItem('token')
      }
    }).then((response) => {
      resolve(response.data);
    }).catch(err => {
      reject(err)
    });
  });
};



// 表单提交方法
util.fetchPost = function (url, params = {}) {
  return new Promise((resolve, reject) => {
    axios({
      method: 'post',
      url: url,
      data: params,
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
        'token': window.localStorage.getItem('token')
      }
    }).then((response) => {
      resolve(response.data);
    }).catch(err => {
      reject(err)
    });
  });
};

// json对象提交方法
util.fetchPostObj = function (url, params = {}) {
  return new Promise((resolve, reject) => {
    axios({
      method: 'post',
      url: url,
      data: params,
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'token': window.localStorage.getItem('token')
      }
    }).then((response) => {
      resolve(response.data);
    }).catch(err => {
      reject(err)
    });
  });
};

// post 请求
util.fetchPostForm = function (url, params = {}) {
  return new Promise((resolve, reject) => {
    axios({
      method: 'post',
      url: url,
      data: params,
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'multipart/form-data',
        'token': window.localStorage.getItem('token')
      }
    }).then((response) => {
      resolve(response.data);
    }).catch(err => {
      reject(err)
    });
  });
};

// get方法
util.fetchGet = function (url, param = {}) {
  let params = {
    params: param
  };
  return new Promise((resolve, reject) => {
    axios.get(`${url}?t=${new Date().getTime()}`, params).then(res => {
      // 加上时间戳 消除ie版本浏览器的缓存
      resolve(res.data);
    }).catch((error) => {
      reject(error);
    });
  });
};

// get方法
util.fetchGetArray = function (url, param = []) {
  let params = {
    params: param
  };
  return new Promise((resolve, reject) => {
    axios.get(`${url}?t=${new Date().getTime()}`, params).then(res => {
      // 加上时间戳 消除ie版本浏览器的缓存
      resolve(res.data);
    }).catch((error) => {
      reject(error);
    });
  });
};
//修改方法
util.fetchPostEdit = function (url, params = {}) {
  return new Promise((resolve, reject) => {
    axios({
      method: 'put',
      url: url,
      data: params,
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'token': window.localStorage.getItem('token')
      }
    }).then((response) => {
      resolve(response.data);
    });
  });
};

//修改方法
util.fetchGetAll = function (url, params = {}) {
  return new Promise((resolve, reject) => {
    axios({
      method: 'get',
      url: url,
      data: params,
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'token': window.localStorage.getItem('token')
      }
    }).then((response) => {
      resolve(response.data);
    }).catch(err => {
      reject(err)
    });
  });
};

//put 方法
util.fetchPut = function (url, params = {}) {
  return new Promise((resolve, reject) => {
    axios({
      method: 'put',
      url: url,
      data: params,
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'token': window.localStorage.getItem('token')
      }
    }).then((response) => {
      resolve(response.data);
    }).catch(err => {
      reject(err)
    });
  });
};

//delect 方法
util.fetchDelete = function (url, params = {}) {
  return new Promise((resolve, reject) => {
    axios({
      method: 'delete',
      url: url,
      data: params,
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'token': window.localStorage.getItem('token')
      }
    }).then((response) => {
      resolve(response.data);
    }).catch(err => {
      reject(err)
    });
  });
};

// 框架方法
util.inOf = function (arr, targetArr) {
  let res = true;
  arr.forEach(item => {
    if (targetArr.indexOf(item) < 0) {
      res = false;
    }
  });
  return res;
};

util.oneOf = function (ele, targetArr) {
  if (targetArr.indexOf(ele) >= 0) {
    return true;
  } else {
    return false;
  }
};

util.showThisRoute = function (itAccess, currentAccess) {
  if (typeof itAccess === 'object' && Array.isArray(itAccess)) {
    return util.oneOf(currentAccess, itAccess);
  } else {
    return itAccess === currentAccess;
  }
};

util.getRouterObjByName = function (routers, name) {
  if (!name || !routers || !routers.length) {
    return null;
  }

  let routerObj = null;
  for (let item of routers) {
    if (item.name === name) {
      return item;
    }
    routerObj = util.getRouterObjByName(item.children, name);
    if (routerObj) {
      return routerObj;
    }
  }
  return null;
};

util.openNewPage = function (vm, name, argu, query) {
  let pageOpenedList = vm.$store.state.app.pageOpenedList;
  let openedPageLen = pageOpenedList.length;
  let i = 0;
  let tagHasOpened = false;
  while (i < openedPageLen) {
    if (name === pageOpenedList[i].name) { // 页面已经打开
      vm.$store.commit('pageOpenedList', {
        index: i,
        argu: argu,
        query: query
      });
      tagHasOpened = true;
      break;
    }
    i++;
  }
  if (!tagHasOpened) {
    let tag = vm.$store.state.app.tagsList.filter((item) => {
      if (item.children) {
        return name === item.children[0].name;
      } else {
        return name === item.name;
      }
    });
    tag = tag[0];
    if (tag) {
      tag = tag.children ? tag.children[0] : tag;
      if (argu) {
        tag.argu = argu;
      }
      if (query) {
        tag.query = query;
      }
      vm.$store.commit('increateTag', tag);
    }
  }
  vm.$store.commit('setCurrentPageName', name);
};

util.toDefaultPage = function (routers, name, route, next) {
  let len = routers.length;
  let i = 0;
  let notHandle = true;
  while (i < len) {
    if (routers[i].name === name && routers[i].children && routers[i].redirect === undefined) {
      route.replace({
        name: routers[i].children[0].name
      });
      notHandle = false;
      next();
      break;
    }
    i++;
  }
  if (notHandle) {
    next();
  }
};

util.fullscreenEvent = function (vm) {
  vm.$store.commit('initCachepage');
  // 权限菜单过滤相关
  vm.$store.commit('updateMenulist');
  // 全屏相关
};

// 自定义方法
function myBrowser() {
  let userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
  let isOpera = userAgent.indexOf("Opera") > -1;
  if (isOpera) {
    return "Opera"
  } //判断是否Opera浏览器
  if (userAgent.indexOf("Firefox") > -1) {
    return "FF";
  } //判断是否Firefox浏览器
  if (userAgent.indexOf("Chrome") > -1) {
    return "Chrome";
  }
  if (userAgent.indexOf("Safari") > -1) {
    return "Safari";
  } //判断是否Safari浏览器
  if (userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1 && !isOpera) {
    return "IE";
  }
  ; //判断是否IE浏览器
  if (userAgent.indexOf("Trident") > -1) {
    return "Edge";
  } //判断是否Edge浏览器
}

// 下载
util.download = function (url, name) {
  // let $a = document.createElement('a');
  // $a.setAttribute("href", url);
  // $a.setAttribute("download", "");
  // let evObj = document.createEvent('MouseEvents');
  // evObj.initMouseEvent( 'click', true, true, window, 0, 0, 0, 0, 0, false, false, true, false, 0, null);
  // $a.dispatchEvent(evObj);

  if (myBrowser() === 'IE' || myBrowser() === 'Edge') {
    SaveAs5(url);
  } else {
    ddownload(url, name);
  }
};

function SaveAs5(imgURL) {
  var oPop = window.open(imgURL, '', 'width=1, height=1, top=5000, left=5000');
  for (; oPop.document.readyState != 'complete';) {
    if (oPop.document.readyState == 'complete') break;
  }
  oPop.document.execCommand('SaveAs');
  oPop.close();
}

function ddownload(src, name) {
  var $a = document.createElement('a');
  $a.setAttribute('href', src);
  $a.setAttribute('target', '_blank');
  $a.setAttribute('download', name);

  var evObj = document.createEvent('MouseEvents');
  evObj.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, false, false, true, false, 0, null);
  $a.dispatchEvent(evObj);
};

function padLeftZero(str) {
  return ('00' + str).substr(str.length);
}

//日期转换（年）
export const dateFormatYear = (dateOrigin) => {
  let dateNew = null;
  if (dateOrigin) {
    dateNew = moment(dateOrigin).format('YYYY')
  }
  return dateNew
}
//日期转换（年月日）
export const changeDateForm = (dateOrigin) => {
  let dateNew = null;
  if (dateOrigin) {
    dateNew = moment(dateOrigin).format('YYYY-MM-DD')
  }
  return dateNew
}
//日期转换（年月日时分）
export const changeDateFormat = (dateOrigin) => {
  let dateNew = null;
  if (dateOrigin) {
    dateNew = moment(dateOrigin).format('YYYY-MM-DD HH:mm:ss')
  }
  return dateNew
}

//获取当前用户权限资源
util.authorityControl = function (params) {
  let userIdentify = JSON.parse(localStorage.getItem('userAccessData'));
  if (!userIdentify) {
    return
  }
  for (let i = 0; i < userIdentify.length; i++) {
    if (userIdentify.length > 0 && userIdentify[i].indexOf(params) != -1) {
      return true;
    }
  }
};

//获取当前用户权限,非UAC
util.getUserPermissions = function(params){
  let userIdentify = JSON.parse(localStorage.getItem('userAccessData'));
  if (!userIdentify) {
    return
  }
  //判断权限数组是否有值,并且包含某权限
    if (userIdentify.length > 0 && userIdentify.indexOf(params) != -1) {
      return true;
    }
};

//日期转换（年月)
export const dateFormatMonth = (dateOrigin) => {
  let dateNew = null;
  if (dateOrigin) {
    dateNew = moment(dateOrigin).format('YYYY-MM')
  }
  return dateNew
}
//日期转换（年月日时分秒）
export const dateFormatSeconds = (dateOrigin) => {
  let dateNew = null;
  if (dateOrigin) {
    dateNew = moment(dateOrigin).format('YYYY-MM-DD HH:mm:ss')
  }
  return dateNew
}
/**
 * @param {*} arr 数组
 * @description 判断数组是否有重复
 */
export const isArrRepeat = (arr) => {
  let hash = {};
  for (let i in arr) {
    if (hash[arr[i]]) {
      return true;
    }
    hash[arr[i]] = true;
  }
  return false;
}

// 13位时间戳转化成yy-mm-dd hh:mm:ss
util.getFormatDate = function (inputTime) {
  if (!inputTime) {
    return '';
  }
  let date = new Date(inputTime);
  let y = date.getFullYear();
  let m = date.getMonth() + 1;
  m = m < 10 ? ('0' + m) : m;
  let d = date.getDate();
  d = d < 10 ? ('0' + d) : d;
  let h = date.getHours();
  h = h < 10 ? ('0' + h) : h;
  let minute = date.getMinutes();
  let second = date.getSeconds();
  minute = minute < 10 ? ('0' + minute) : minute;
  second = second < 10 ? ('0' + second) : second;
  return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second;
};

// 时间戳转化成yy-mm-dd
util.getDate = function (inputTime) {
  if (!inputTime) {
    return '';
  }
  let date = moment(inputTime).toDate();
  // let date = new Date(inputTime);
  let y = date.getFullYear();
  let m = date.getMonth() + 1;
  m = m < 10 ? ('0' + m) : m;
  let d = date.getDate();
  d = d < 10 ? ('0' + d) : d;
  return y + '-' + m + '-' + d;
};

// 时间戳转化成hh:mm:ss
util.getTime = function (inputTime) {
  let date = moment(inputTime).toDate();
  let h = date.getHours();
  h = h < 10 ? ('0' + h) : h;
  let minute = date.getMinutes();
  let second = date.getSeconds();
  minute = minute < 10 ? ('0' + minute) : minute;
  second = second < 10 ? ('0' + second) : second;
  return h + ':' + minute + ':' + second;
};


// 时间戳转化成hh:mm
util.getDivisionTime = function (inputTime) {
  let date = moment(inputTime).toDate();
  let h = date.getHours();
  h = h < 10 ? ('0' + h) : h;
  let minute = date.getMinutes();
  minute = minute < 10 ? ('0' + minute) : minute;
  return h + ':' + minute;
};

// 格式化时间
util.formatDate = function (date, fmt) {
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
  }
  ;
  let o = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds()
  };
  for (let k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      let str = o[k] + '';
      fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : padLeftZero(str));
    }
  }
  return fmt;
};

// 获取选中月的第一天和最后一天
util.getMonthFirstAndLastQuarterDay = function (year, month) {
  let firstDate = year + '-' + month + '-01';
  let day = new Date(year, month, 0);
  let lastDate = year + '-' + month + '-' + day.getDate();// 获取当月最后一天日期
  return [firstDate, lastDate];
};

// 获取选中月的第一天和最后一天
util.getMonthFirstAndLastQuarterDay1 = function (year, month, lastYear, lastMonth) {
  let firstDate = year + '-' + month + '-01';
  let day = new Date(lastYear, lastMonth, 0);
  let lastDate = lastYear + '-' + lastMonth + '-' + day.getDate();// 获取当月最后一天日期
  return [firstDate, lastDate];
};

// 获取选中年的第一天和最后一天
util.getYearFirstAndLastQuarterDay = function (year) {
  let firstDate = year + '-' + '01-01';
  let lastDate = year + '-' + '12-31';
  return [firstDate, lastDate];
};
// 获取选中年的第一天和最后一天
util.getYearFirstAndLastQuarterDay1 = function (year, lastYear) {
  let firstDate = year + '-' + '01-01';
  let lastDate = lastYear + '-' + '12-31';
  return [firstDate, lastDate];
};

/* //获取选本周的第一天和最后一天
util.getWeekFirstAndLastQuarterDay =function (week) {
    const end = new Date();
    const start = new Date();
    start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
    return [start, end];
}; */

// 校验手机号
util.validatePhoneNumber = (rule, value, callback) => {
  let myreg = /^((0\d{2,3}-\d{7,8})|(1[1234567890]\d{9}))$/;
  if (!myreg.test(value)) {
    callback(new Error('请输入正确的电话号码'));
  } else {
    callback();
  }
};
// 校验身份证号
util.validateIdentityCard = (rule, value, callback) => {
  let myreg = /^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|[xX])$/;
  if (!myreg.test(value)) {
    callback(new Error('请输入正确的身份证号'));
  } else {
    callback();
  }
};

// 校验纯数字
util.validateNumber = (rule, value, callback) => {
  let myreg = /^\d*$/;
  if (!myreg.test(value)) {
    callback(new Error('请输入纯数字'));
  } else {
    callback();
  }
};

// 校验密码  只能输入6到20位字符、数字和下划线
util.validatePassword = (rule, value, callback) => {
  let myreg = /^[a-z0-9]\w{5,19}$/i;
  if (!myreg.test(value)) {
    callback(new Error('请输入6到20位字符、数字或下划线'));
  } else {
    callback();
  }
};

util.isNumber = (str) => {
  let reg = /^\d*$/;
  return reg.test(str);
};
util.isIdentityCard = (str) => {
  let reg = /^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|[xX])$/;
  return reg.test(str);
};
// 校验手机号
util.isPhoneNumber = (str) => {
  let reg = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
  return reg.test(str);
};
// 校验邮箱
util.isEmail = (str) => {
  let reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
  return reg.test(str);
};
//去空格
util.deleteSpace = (str) => {
  return str.replace(/\s+/g, "");
}
// 校验ip
util.isIP = (str) => {
  let reg = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;
  return reg.test(str);
};

// 校验小数点位数（小数点前面最多6位数字，小数点后面最多2位数字）
util.isDecimals = (str) => {
  let reg = /^\d{1,6}(\.\d{1,2})?$/;
  return reg.test(str);
};
// 校验小数点位数（小数点前面最多4位数字，小数点后面最多2位数字）
util.validateDecimals = (str) => {
  let reg = /^[1-9]{1}(\d{0,5})?(\.\d{1,2})?$|^[0](\.\d{1}[1-9]{1})$|^[0](\.[1-9]{1}(\d{1})?)$/;
  return reg.test(str);
};
// 校验小数点位数（小数点前面最多6位数字，小数点后面最多2位数字），可以为负数
util.isPosiNegaDecimals = (str) => {
  let reg = /^[+-]?\d{1,6}(\.\d{1,2})?$/;
  return reg.test(str);
};
// 校验小数点位数（小数点前面最多3位数字，小数点后面最多2位数字），可以为负数
util.isPosiNegaDecimalsThird = (str) => {
  let reg = /^[+-]?\d{1,3}(\.\d{1,2})?$/;
  return reg.test(str);
};
// 同时验证手机号和座机号
util.isPhone = (str) => {
  let isPhone = /^([0-9]{3,4}-)?[0-9]{7,8}$/;
  let isMob = /^((\+?86)|(\+86\+86))?(13[012356789][0-9]{8}|15[012356789][0-9]{8}|18[02356789][0-9]{8}|147[0-9]{8}|1349[0-9]{7})$/;
  if (isMob.test(str) || isPhone.test(str)) {
    return true;
  } else {
    return false;
  }
};
// 校验正整数 positive integer
util.isPositiveInteger = (str) => {
  let reg = /^[1-9]\d*$/;
  return reg.test(str);
};
// 校验密码  只能输入6到20位字符、数字和下划线
util.isPassword = (str) => {
  let reg = /^[a-z0-9]\w{5,19}$/i;
  return reg.test(str);
};
// 只保留省的名称
util.checkProvinceName = (str) => {
  return str.replace(/回族自治区/g, '').replace(/维吾尔自治区/g, '').replace(/壮族自治区/g, '').replace(/特别行政区/g, '').replace(/市/g, '').replace(/省/g, '').replace(/自治区/g, '');
};
// 判断是否是微信浏览器的函数
util.isWeiXin = () => {
  // window.navigator.userAgent属性包含了浏览器类型、版本、操作系统类型、浏览器引擎类型等信息，这个属性可以用来判断浏览器类型
  let ua = window.navigator.userAgent.toLowerCase();
  // 通过正则表达式匹配ua中是否含有MicroMessenger字符串
  if (ua.match(/MicroMessenger/i) == 'micromessenger') {
    return true;
  } else {
    return false;
  }
};
// 判断 浏览器
util.IEVersion = () => {
  var userAgent = navigator.userAgent; // 取得浏览器的userAgent字符串
  var isIE = userAgent.indexOf('compatible') > -1 && userAgent.indexOf('MSIE') > -1; // 判断是否IE<11浏览器
  var isEdge = userAgent.indexOf('Edge') > -1 && !isIE; // 判断是否IE的Edge浏览器
  var isIE11 = userAgent.indexOf('Trident') > -1 && userAgent.indexOf('rv:11.0') > -1;
  if (isIE) {
    var reIE = new RegExp('MSIE (\\d+\\.\\d+);');
    reIE.test(userAgent);
    var fIEVersion = parseFloat(RegExp['$1']);
    if (fIEVersion == 7) {
      return 7;
    } else if (fIEVersion == 8) {
      return 8;
    } else if (fIEVersion == 9) {
      return 9;
    } else if (fIEVersion == 10) {
      return 10;
    } else {
      return 6;// IE版本<=7
    }
  } else if (isEdge) {
    return 'edge';// edge
  } else if (isIE11) {
    return 11; // IE11
  } else {
    return -1;// 不是ie浏览器
  }
};
// 营业执照长度须为18位数字和字母
util.isBusinessLicense = function (Code) {
  var patrn = /^[0-9A-Z]+$/;
  // 18位校验及大写校验
  if ((Code.length != 18) || (patrn.test(Code) == false)) {
    console.info('不是有效的统一社会信用编码！');
    return false;
  } else {
    var Ancode;// 统一社会信用代码的每一个值
    var Ancodevalue;// 统一社会信用代码每一个值的权重
    var total = 0;
    var weightedfactors = [1, 3, 9, 27, 19, 26, 16, 17, 20, 29, 25, 13, 8, 24, 10, 30, 28];// 加权因子
    var str = '0123456789ABCDEFGHJKLMNPQRTUWXY';
    // 不用I、O、S、V、Z
    for (var i = 0; i < Code.length - 1; i++) {
      Ancode = Code.substring(i, i + 1);
      Ancodevalue = str.indexOf(Ancode);
      total = total + Ancodevalue * weightedfactors[i];
      // 权重与加权因子相乘之和
    }
    var logiccheckcode = 31 - total % 31;
    if (logiccheckcode == 31) {
      logiccheckcode = 0;
    }
    var Str = '0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,J,K,L,M,N,P,Q,R,T,U,W,X,Y';
    var Array_Str = Str.split(',');
    logiccheckcode = Array_Str[logiccheckcode];

    var checkcode = Code.substring(17, 18);
    if (logiccheckcode != checkcode) {
      console.info('不是有效的统一社会信用编码！');
      return false;
    } else {
      console.info('yes');
    }
    return true;
  }
};
// 经度： -180.0～+180.0（整数部分为0～180，必须输入6位小数）
util.longitude = (str) => {
  let reg = /^-?(180(\.0{0,6})?|(1[0-7][0-9]|[1-9]?[0-9])(\.[0-9]{0,20}))$/;
  return reg.test(str);
};

// 纬度： -90.0～+90.0（整数部分为0～90，必须输入6位小数）
util.latitude = (str) => {
  let reg = /^-?(90(\.0{0,6})?|[1-8]?[0-9](\.[0-9]{0,20})?)$/;
  return reg.test(str);
};
// 整数或小数
util.integerDecimal = (str) => {
  let re = '^[0-9]+\.?[0-9]*$';
  let reg = new RegExp(re);
  return reg.test(str);
};
// 小数
util.decimal = (str) => {
  let reg = /^[1-9]?[0-9]*\.[0-9]*$/;
  return reg.test(str);
};
// 车牌号码校验
util.vehicleNumber = (str) => {
  let reg = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$/;
  return reg.test(str);
};
// 对时分校验
util.hour = (str) => {
  let reg = /^(0\d{1}|1\d{1}|2[0-3]):([0-5]\d{1})$/;
  return reg.test(str);
};
// 6位数字以内
util.number = (str) => {
  let reg = new RegExp(/^\d{0,6}$/);
  return reg.test(str);
};
// 传真号正则（传真格式为:XXX-12345678或XXXX-1234567或XXXX-12345678）
util.fax = (str) => {
  let reg = /^(\d{3,4}-)?\d{7,8}$/;
  return reg.test(str);
};
// 小数点前10位，小数点后两位
util.isTenNumber = (str) => {
  let reg = /^\d{1,10}(\.\d{1,2})?$/;
  return reg.test(str);
};
// qq号
util.isQQ = (str) => {
  let reg = /^[0-9]{5,10}$/;
  return reg.test(str);
};

export const showTitle = (item, vm) => {
  return (item.meta && item.meta.title);
}

util.toArray = obj => {
  if (!obj) {
    return []
  }
  if (obj instanceof Array) {
    return obj
  }
  if (obj.length || obj.length === 0) {
    return Array.from(obj)
  }
}

util.toObject = obj => {
  if (!obj) {
    return {}
  } else {
    return obj
  }
}
util.wsUrl = (host) => {
  let schema
  switch (window.location.protocol) {
    case 'http:':
      schema = 'ws:'
      break
    case 'https:':
      schema = 'wss:'
      break
    default:
      alert('异常协议！')
  }
  //host = '192.168.2.113:8080'
    host = host || window.location.host
  return schema + '//' + host;
}

export function sleep(time) {
  return new Promise((resolve) => setTimeout(resolve, time))
}

// util.authority = () => {
//   let userIdentify = JSON.parse(localStorage.getItem('userAccessData'));
//   if (!userIdentify) {
//     return;
//   }
//   for (let i = 0; i < appRouter.length; i++) {
//     for (let j = 0; j < appRouter[i].children.length; j++) {
//       if (util.oneOf(appRouter[i].children[j].meta.access, userIdentify)) {
//         appRouter[i].children[j].flag = true;
//       } else {
//         appRouter[i].children[j].flag = false;
//       }
//     }
//   }
// }
util.getArray = (array) => {
  const o = []
  for (const it of array) {
    o[it['key']] = []
  }
  return o;
}

// 轮询，当满足条件时做某事
util.doWhen = async (when, todo) => {
  const now = await when()
  while (!now) {
    await sleep(50)
  }
  return await todo()
}
export default util;
